<?php

/**
 *   OPENSHOP 管理中心积分兑换商品程序文件
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: exchange_goods.php,v 1.0 2009/06/19 09:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');

/*初始化数据交换对象 */
$exc   = new exchange($os->table("exchange_goods"), $db, 'goods_id', 'exchange_integral');

/*------------------------------------------------------ */
//-- 商品列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    /* 权限判断 */
    admin_priv();

    /* 取得过滤条件 */
    $filter = array();
    $smarty->assign('ur_here',      '积分换购商品列表');
    $smarty->assign('action_link',  array('text' => '添加积分换购商品', 'href' => 'exchange_goods.php?act=add'));
    $smarty->assign('full_page',    1);
    $smarty->assign('filter',       $filter);
    
    $goods_list = get_exchange_goodslist();
    
    $sql = "Select * from ".$os->table('user_rank');
    $user_ranks = $db->getAll($sql);
    
    $arr = array();
    foreach ($goods_list['arr'] as $uu)
    {
    	$uu['user_rank'] = get_ranks_name($uu['user_rank'],$user_ranks);
    	$arr[]  = $uu;
    }
    $smarty->assign('goods_list',    $arr);
    $smarty->assign('filter',        $goods_list['filter']);
    $smarty->assign('record_count',  $goods_list['record_count']);
    $smarty->assign('page_count',    $goods_list['page_count']);

    $sort_flag  = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    
	$smarty->display('exchange_goods_list.tpl');
	
}

/*------------------------------------------------------ */
//-- 翻页，排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    check_authz_json('exchange_goods');

    $goods_list = get_exchange_goodslist();

    $smarty->assign('goods_list',    $goods_list['arr']);
    $smarty->assign('filter',        $goods_list['filter']);
    $smarty->assign('record_count',  $goods_list['record_count']);
    $smarty->assign('page_count',    $goods_list['page_count']);

    $sort_flag  = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('exchange_goods_list.htm'), '',
        array('filter' => $goods_list['filter'], 'page_count' => $goods_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加商品
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add')
{
    /* 权限判断 */
    admin_priv('add_exchange_goods');

    /*初始化*/
    $goods = array();
    $goods['is_exchange'] = 1;
    $goods['is_hot']      = 0;
    $goods['option']      = '<option value="0">'.'请首先搜索商品生成商品列表'.'</option>';

    $smarty->assign('goods',       $goods);
    $smarty->assign('ur_here',     '添加新商品');
    $smarty->assign('action_link', array('text' => '积分换购商品列表', 'href' => 'exchange_goods.php?act=list'));
    $smarty->assign('form_action', 'insert');
    
    $sql = "Select * from ".$os->table('user_rank');
    $user_ranks = $db->getAll($sql);
    $smarty->assign('user_ranks', $user_ranks);

    assign_query_info();
	
	$smarty->display('exchange_goods_info.tpl');
}

/*------------------------------------------------------ */
//-- 添加商品
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'insert')
{
    /* 权限判断 */
    admin_priv('add_exchange_goods');

    /*检查是否重复*/
    $is_only = $exc->is_only('goods_id', $_POST['goods_id'],0, " goods_id ='$_POST[goods_id]'");

    if (!$is_only)
    {
        sys_msg('商品已经存在', 1);
    }

    /*插入数据*/
    $add_time = gmtime();
    if (empty($_POST['goods_id']))
    {
        $_POST['goods_id'] = 0;
    }

    $sql = "INSERT INTO ".$os->table('exchange_goods')."(goods_id, exchange_integral, exchange_price, is_exchange, is_hot, user_rank,is_stop) ".
            "VALUES ('$_POST[goods_id]', '$_POST[exchange_integral]', '$_POST[exchange_price]', '1', '$_POST[is_hot]','$_POST[user_rank_ids]','0')";
    $db->query($sql);

    $link[0]['text'] = '继续添加';
    $link[0]['href'] = 'exchange_goods.php?act=add';

    $link[1]['text'] = '返回积分商品列表';
    $link[1]['href'] = 'exchange_goods.php?act=list';

    admin_log($_POST['goods_id'],'add','exchange_goods');

    clear_cache_files(); // 清除相关的缓存文件

    sys_msg('积分换购商品添加成功',0, $link);
}

/*------------------------------------------------------ */
//-- 编辑
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'edit')
{
    /* 权限判断 */
    admin_priv('edit_exchange_goods');

    /* 取商品数据 */
    $sql = "SELECT eg.goods_id, eg.exchange_integral,eg.exchange_price,eg.is_exchange, eg.is_hot, eg.is_stop,g.goods_name ,eg.user_rank".
           " FROM " . $os->table('exchange_goods') . " AS eg ".
           "  LEFT JOIN " . $os->table('goods') . " AS g ON g.goods_id = eg.goods_id ".
           " WHERE eg.goods_id='$_REQUEST[id]'";
    $goods = $db->GetRow($sql);
    $goods['option']  = '<option value="'.$goods['goods_id'].'">'.$goods['goods_name'].'</option>';

    $smarty->assign('goods',       $goods);
    $smarty->assign('ur_here',     '编辑积分换购商品');
    $smarty->assign('action_link', array('text' => '积分换购商品列表', 'href' => 'exchange_goods.php?act=list&' . list_link_postfix()));
    $smarty->assign('form_action', 'update');
	
    $sql = "Select * from ".$os->table('user_rank');
    $ranks = $db->getAll($sql);
   	
    
    foreach ($ranks as $key => $val){
    	$result = is_user_rank_selected($val["rank_id"],$goods["user_rank"]);

    	$user_ranks[$key]['checked'] = $result;
    	$user_ranks[$key]['rank_id'] = $val["rank_id"];
    	$user_ranks[$key]['rank_name'] = $val["rank_name"];
    }
    $smarty->assign('user_ranks', $user_ranks);

    assign_query_info();
	
	$smarty->display('exchange_goods_info.tpl');
}

/*------------------------------------------------------ */
//-- 编辑
/*------------------------------------------------------ */
if ($_REQUEST['act'] =='update')
{
    /* 权限判断 */
    admin_priv('edit_exchange_goods');

    if (empty($_POST['goods_id']))
    {
        $_POST['goods_id'] = 0;
    }
	
    if ($exc->edit("exchange_integral='$_POST[exchange_integral]', exchange_price='$_POST[exchange_price]',user_rank='$_POST[user_rank_ids]',is_exchange='1', is_hot='$_POST[is_hot]', is_stop='$_POST[is_stop]' ", $_POST['goods_id']))
    {
        $link[0]['text'] = '返回商品列表';
        $link[0]['href'] = 'exchange_goods.php?act=list&' . list_link_postfix();
		
        admin_log($_POST['goods_id'], 'edit', 'exchange_goods');
		
        clear_cache_files();
        sys_msg('更新成功', 0, $link);
    }
    else
    {
        die($db->error());
    }
}

/*------------------------------------------------------ */
//-- 编辑使用积分值
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_exchange_integral')
{
    //check_authz_json('edit_exchange_integral');

    $id                = intval($_POST['id']);
    $exchange_integral = floatval($_POST['val']);

    /* 检查文章标题是否重复 */
    if ($exchange_integral < 0 || $exchange_integral == 0 && $_POST['val'] != "$goods_price")
    {
        make_json_error('积分值为空或不是数字');
    }
    else
    {
        if ($exc->edit("exchange_integral = '$exchange_integral'", $id))
        {
            clear_cache_files();
            admin_log($id, 'edit', 'exchange_goods');
            make_json_result(stripslashes($exchange_integral));
        }
        else
        {
            make_json_error($db->error());
        }
    }
}

/*------------------------------------------------------ */
//-- 切换是否兑换
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_exchange')
{
    //check_authz_json('toggle_exchange');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_exchange = '$val'", $id);
    clear_cache_files();

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 切换是否停用
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_stop')
{
    //check_authz_json('toggle_stop');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_stop = '$val'", $id);
    clear_cache_files();

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 切换是否兑换
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_hot')
{
    //check_authz_json('toggle_hot');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);

    $exc->edit("is_hot = '$val'", $id);
    clear_cache_files();

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 批量删除商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch_remove')
{
    admin_priv('drop_exchange_goods_all');

    if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
    {
        sys_msg('没有选择批量删除商品', 1);
    }

    $count = 0;
    foreach ($_POST['checkboxes'] AS $key => $id)
    {
        if ($exc->drop($id))
        {
            admin_log($id,'remove','exchange_goods');
            $count++;
        }
    }

    $lnk[] = array('text' => '返回商品列表', 'href' => 'exchange_goods.php?act=list');
    sys_msg(sprintf('您已经成功删除 %d 件商品', $count), 0, $lnk);
}

/*------------------------------------------------------ */
//-- 删除商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    //check_authz_json('drop_exchange_goods');

    $id = intval($_GET['id']);
    if ($exc->drop($id))
    {
        admin_log($id,'remove','article');
        clear_cache_files();
    }

    $url = 'exchange_goods.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 搜索商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'search_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);

    make_json_result($arr);
}

/* 获得商品列表 */


function get_exchange_goodslist()
{
    $result = get_filter();
    if ($result === false)
    {
        $filter = array();
        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'eg.goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = '';
        if (!empty($filter['keyword']))
        {
            $where = " AND g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
        }

        /* 文章总数 */
        $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['os']->table('exchange_goods'). ' AS eg '.
               'LEFT JOIN ' .$GLOBALS['os']->table('goods'). ' AS g ON g.goods_id = eg.goods_id '.
               'WHERE 1 ' .$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        $filter = page_and_size($filter);

        /* 获取文章数据 */
        $sql = 'SELECT eg.* , g.goods_name '.
               'FROM ' .$GLOBALS['os']->table('exchange_goods'). ' AS eg '.
               'LEFT JOIN ' .$GLOBALS['os']->table('goods'). ' AS g ON g.goods_id = eg.goods_id '.
               'WHERE 1 ' .$where. ' ORDER by '.$filter['sort_by'].' '.$filter['sort_order'];

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $arr[] = $rows;
    }
    return array('arr' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}


function is_user_rank_selected($rank_id,$seleced)
{
	$ranks = split(',',$seleced);
	foreach ($ranks as $value)
	{
		if($rank_id == $value){
			return 1;
		}
	}
	return 0;
}

function get_ranks_name($rankids,$user_ranks)
{
	$arr_rankids = split(',',$rankids);
	$v = "";
	foreach ($arr_rankids as $rank)
	{
		if($v == ""){
			$v = $v.get_rank_name($rank,$user_ranks);
		}else{
			$v = $v." | ".get_rank_name($rank,$user_ranks);
		}
	}
	return $v;
}

function get_rank_name($rank,$user_ranks)
{
	foreach ($user_ranks as $user_rank)
	{
		if($user_rank['rank_id']==$rank)
			return $user_rank['rank_name'];
	}
	return "";
	
}
?>